package com.haifeng.Login.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/index.jsp")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//        chain.doFilter(request, response);
        HttpServletRequest request = (HttpServletRequest) req;
        String uri = request.getRequestURI();
        if (uri.contains("/login.jsp") || uri.contains("/login") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/img/")) {
            //包含，想登录，放行
            System.out.println("想登陆,放行");
            chain.doFilter(req, resp);
        } else {
            Object user = request.getSession().getAttribute("user");
            System.out.println("访问的不是login.jsp");
            //不包含，检查session 如果有用户信息，放行
            if (user != null) {
                System.out.println("登陆成功，放行");
                //用户登陆成功！，放行
                chain.doFilter(req, resp);
            } else {
                System.out.println("未登陆");
                //用户未登陆，跳转到登陆界面
                request.getRequestDispatcher("/login.jsp").forward(req, resp);
//                HttpServletResponse response = (HttpServletResponse) resp;
//                response.sendRedirect("/login.jsp");
            }
        }

    }
}
